package com.jxc.controller.admin;

import com.jxc.entity.admin.Stock;
import com.jxc.entity.admin.OrderIn;
import com.jxc.entity.admin.OrderInDetail;
import com.jxc.entity.admin.User;
import com.jxc.page.admin.Page;
import com.jxc.service.admin.OrderInService;
import com.jxc.service.admin.StockService;
import com.jxc.service.admin.SupplierService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: 进货单
 */
@Controller
@RequestMapping("/admin/orderin")
public class OrderInController {

    @Autowired
    private OrderInService orderinService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private StockService stockService;

    /**
     * 进入供应商查询界面
     */
    @RequestMapping(value="/list",method= RequestMethod.GET)
    public ModelAndView list(ModelAndView model){
        model.setViewName("orderin/list");
        return model;
    }

    /**
     * 查询
     */
    @ResponseBody
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public Map<String, Object> getList(
            @RequestParam(value="payType",required=false) Integer payType,
            @RequestParam(value="status",required=false) Integer status,
            @RequestParam(value="minMoney",required=false) Float minMoney,
            @RequestParam(value="maxMoney",required=false) Float maxMoney,
            @RequestParam(value="operator",defaultValue="") String operator,Page page
    ){
        Map<String, Object> ret = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("operator", operator);
        if(payType != null){
            queryMap.put("payType", payType);
        }
        if(status != null){
            queryMap.put("status", status);
        }
        if(minMoney != null){
            queryMap.put("minMoney", minMoney);
        }
        if(maxMoney != null){
            queryMap.put("maxMoney", maxMoney);
        }
        queryMap.put("offset", page.getOffset());
        queryMap.put("pageSize", page.getRows());
        ret.put("total", orderinService.getTotal(queryMap));
        ret.put("rows", orderinService.getList(queryMap));
        return ret;
    }

    /**
     * 添加一条记录
     */
    @ResponseBody
    @RequestMapping(value = "add",method = RequestMethod.POST)
    public Map<String, String> add(String productList, OrderIn orderIn, HttpServletRequest request){
        Map<String, String> ret = new HashMap<>();
        if(StringUtils.isEmpty(productList)){
            ret.put("type", "error");
            ret.put("msg", "请至少选择一个商品信息!");
            return ret;
        }
        if(orderIn == null){
            ret.put("type", "error");
            ret.put("msg", "请填写正确的进货单信息!");
            return ret;
        }
        JSONArray productArray = JSONArray.fromObject(productList);
        float money = 0;
        int num = 0;
        List<Stock> stockList = new ArrayList<>();
        for(int i = 0; i < productArray.size(); i++){
            JSONObject jsonObject = productArray.getJSONObject(i);
            OrderInDetail orderInDetail = new OrderInDetail();
            orderInDetail.setProductName(jsonObject.getString("name"));
            orderInDetail.setProductNum(jsonObject.getInt("productNum"));
            orderInDetail.setPrice(Float.valueOf(jsonObject.getString("price")));
            orderInDetail.setMoney(orderInDetail.getPrice() * orderInDetail.getProductNum());
            orderIn.getOrderInDetailList().add(orderInDetail);
            money += orderInDetail.getMoney();
            num += orderInDetail.getProductNum();
            Stock stock = new Stock();
            stock.setProductId(Long.valueOf(jsonObject.getInt("id")+""));
            stock.setProductNum(orderInDetail.getProductNum());
            stock.setCreateTime(new Date());
            stock.setSellNum(0);
            stockList.add(stock);
        }
        orderIn.setMoney(money);
        orderIn.setProductNum(num);
        User admin = (User)request.getSession().getAttribute("admin");
        orderIn.setOperator(admin.getUsername());
        orderIn.setCreateTime(new Date());
        if(orderinService.add(orderIn) <= 0){
            ret.put("type", "error");
            ret.put("msg", "添加失败，请联系管理员!");
            return ret;
        }
        //进行入库操作
        addStock(stockList);
        ret.put("type", "success");
        ret.put("msg", "添加成功!");
        return ret;
    }
    /**
     * 商品入库
     */
    private void addStock(List<Stock> stockList){
        for(Stock stock : stockList){
            Stock existStock = stockService.findByProductId(stock.getProductId());
            if(existStock == null){
                //表示库存里还没有这个商品
                stockService.add(stock);
                continue;
            }
            //走到这里表示数据库中已经存在，则更新商品数量
            existStock.setProductNum(existStock.getProductNum() + stock.getProductNum());
            stockService.edit(existStock);
        }
    }

    /**
     * 修改支付状态为已支付
     */
    @RequestMapping(value="edit",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> edit(OrderIn orderIn){
        Map<String, String> ret = new HashMap<>();
        if(orderIn == null){
            ret.put("type", "error");
            ret.put("msg", "请选择正确的进货单信息!");
            return ret;
        }
        orderIn.setStatus(1);
        if(orderinService.edit(orderIn) <= 0){
            ret.put("type", "error");
            ret.put("msg", "编辑失败，请联系管理员!");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "编辑成功!");
        return ret;
    }

    /**
     * 删除
     */
    @RequestMapping(value="delete",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> delete(@RequestParam(value = "ids") String ids){
        Map<String, String> ret = new HashMap<>();
        if(StringUtils.isEmpty(ids)){
            ret.put("type", "error");
            ret.put("msg", "选择要删除的数据！");
            return ret;
        }
        if(ids.contains(",")){
            ids = ids.substring(0,ids.length()-1);
        }
        if(orderinService.deleteByIds(ids) <= 0){
            ret.put("type", "error");
            ret.put("msg", "删除失败，请联系管理员！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "删除成功！");
        return ret;
    }

}
